package tree.leetcode_103_medium;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class BestSolution {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }
        dfs(root, 0, lists);
        return lists;
    }

    public void dfs(TreeNode root, int level, List<List<Integer>> res) {
        if (level >= res.size()) {
            List<Integer> temp = new LinkedList<>();
            temp.add(root.val);
            res.add(temp);
        } else {
            if (level % 2 == 0) {
                res.get(level).add(root.val);
            } else {
                res.get(level).add(0, root.val);
            }
        }
        if(root.left != null) dfs(root.left, level + 1, res);
        if(root.right != null) dfs(root.right, level + 1, res);
    }
}
